import { Controller, Get, Post, Delete, Param, Body, Req, BadRequestException, Query } from '@nestjs/common';
import { CommentService } from './comment.service';
import { CreateCommentDto, CommentResponseDto } from '../../dto/comment.dto';
import type { Request } from 'express';
import { User } from '../../entities/user.entity';
import { ApiTags, ApiOperation, ApiResponse, ApiBody, ApiParam, ApiQuery } from '@nestjs/swagger';
import { Public } from 'src/common/decorators/public.decorator';

@ApiTags('评论管理')
@Controller('api/comments')
export class CommentController {
  constructor(private readonly commentService: CommentService) {}

  @Post()
  @ApiOperation({
    summary: '创建评论',
    description: '为文章创建新的评论',
  })
  @ApiBody({
    type: CreateCommentDto,
    description: '评论信息',
  })
  @ApiResponse({
    status: 201,
    description: '创建成功',
    type: CommentResponseDto,
  })
  @ApiResponse({
    status: 400,
    description: '用户未登录',
  })
  @ApiResponse({
    status: 404,
    description: '文章不存在',
  })
  create(
    @Body() createCommentDto: CreateCommentDto,
    @Req() req: Request
  ): Promise<CommentResponseDto> {
    const user = (req as any).user as User;
    if (!user) {
      throw new BadRequestException('用户未登录');
    }
    return this.commentService.create(createCommentDto, user.id);
  }

  @Public()
  @Get('article/:articleId')
  @ApiOperation({
    summary: '获取文章评论',
    description: '根据文章ID获取评论列表，支持分页',
  })
  @ApiParam({
    name: 'articleId',
    description: '文章ID',
    example: '1',
  })
  @ApiQuery({
    name: 'page',
    description: '页码',
    required: false,
    default: 1,
  })
  @ApiQuery({
    name: 'pageSize',
    description: '每页数量',
    required: false,
    default: 10,
  })
  @ApiResponse({
    status: 200,
    description: '获取成功',
  })
  findByArticleId(
    @Param('articleId') articleId: string,
    @Query('page') page: number = 1,
    @Query('pageSize') pageSize: number = 10
  ): Promise<{ items: CommentResponseDto[], total: number, page: number, pageSize: number, hasMore: boolean }> {
    return this.commentService.findByArticleId(+articleId, page, pageSize);
  }

  @Delete(':id')
  @ApiOperation({
    summary: '删除评论',
    description: '删除指定的评论（仅评论作者可删除）',
  })
  @ApiParam({
    name: 'id',
    description: '评论ID',
    example: '1',
  })
  @ApiResponse({
    status: 204,
    description: '删除成功',
  })
  @ApiResponse({
    status: 400,
    description: '用户未登录',
  })
  @ApiResponse({
    status: 403,
    description: '无权限删除',
  })
  @ApiResponse({
    status: 404,
    description: '评论不存在',
  })
  remove(@Param('id') id: string, @Req() req: Request): Promise<void> {
    const user = (req as any).user as User;
    if (!user) {
      throw new BadRequestException('用户未登录');
    }
    return this.commentService.remove(+id, user.id);
  }
}